<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        :column="column"
        :getList="getList"
        uniqueId="mesProcessMaterialTable"
        @handleOperateEvent="handleOperateEvent"
      >
      </ele-page>
    </div>
    <!-- 新增弹窗 -->
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
      size="50%"
      ref="addEleFormDrawer"
    >
      <!-- 工艺查询 -->
      <template v-slot:technologyName="{ formData }">
        <el-input v-model="formData.technologyName" readonly>
          <i slot="suffix" class="el-input__icon el-icon-circle-close" style="cursor: pointer;" @click="formData.technologyName = ''"></i>
          <template slot="append">
            <el-button type="primary" icon="el-icon-search" @click="technologyDialogVisible = true"> </el-button>
          </template>
        </el-input>
      </template>
      <!-- 产品查询，就是物料查询 -->
      <template v-slot:prodName="{ formData }">
        <el-input :value="formData.prodName" readonly>
          <template slot="append">
            <el-button type="primary" icon="el-icon-search" @click="handleAddMaterial('product')"> </el-button>
          </template>
        </el-input>
      </template>
      <!-- 系列查询 -->
      <template v-slot:seriesName="{ formData }">
        <el-input :value="formData.seriesName" readonly>
          <template slot="append">
            <el-button type="primary" icon="el-icon-search" @click="seriesDialogVisible = true"> </el-button>
          </template>
        </el-input>
      </template>
      <!-- 编辑时的物料查询 -->
      <template v-slot:materialCode="{ formData }">
        <el-input :value="formData.materialCode" readonly>
          <template slot="append">
            <el-button type="primary" icon="el-icon-search" @click="handleAddMaterial('materialCode')"> </el-button>
          </template>
        </el-input>
      </template>
      <!-- 编辑时的正则表达式查询 -->
      <template v-slot:regularContent="{ formData }">
        <el-input :value="formData.regularContent" :disabled="formData.isKey === '0'" readonly>
          <template slot="append">
            <el-button type="primary" icon="el-icon-search" :disabled="formData.isKey === '0' || dialogStatus === 'detail'" @click="regularDialogVisible = true"> </el-button>
          </template>
        </el-input>
      </template>
    </ele-form-drawer>

    <!-- 物料列表弹窗 -->
    <ele-dialog-table
      :title="$t('mesSalesOrder.materialQuery')"
      width="1200px"
      :visible.sync="materialDialogVisible"
      :formConfig="materialSearchConfig"
      :column="materialColumn"
      :getList="getMaterialList"
      :hasFooter="true"
      :footer="materialDialogFooter"
      :otherParam="otherParam"
      @customEvent="changeMaterialDialog"
      @getSelectData="getSelectedMaterial"
    >
    </ele-dialog-table>

    <!-- 工艺列表弹窗 -->
    <ele-dialog-table
      :title="$t('mesProcessMaterial.technologyQuery')"
      width="1200px"
      :visible.sync="technologyDialogVisible"
      :formConfig="technologySearchConfig"
      :column="technologyColumn"
      :getList="getTechnologyList"
      :hasFooter="true"
      :footer="technologyDialogFooter"
      @customEvent="changeTechnologyDialog"
      @getSelectData="getSelectedTechnology"
    >
    </ele-dialog-table>

    <!-- 正则表达式弹窗 -->
    <ele-dialog-table
      :title="$t('mesProcess.regularQuery')"
      width="800px"
      :visible.sync="regularDialogVisible"
      :formConfig="regularSearchConfig"
      :column="regularColumn"
      :getList="getRegularList"
      :hasFooter="true"
      :footer="regularDialogFooter"
      @customEvent="changeRegularDialog"
      @getSelectData="getSelectedRegular"
    >
    </ele-dialog-table>

    <!-- 系列弹窗 -->
    <ele-dialog-table
      :title="$t('mesProcessMaterial.seriesQuery')"
      width="800px"
      :visible.sync="seriesDialogVisible"
      :formConfig="seriesSearchConfig"
      :column="seriesColumn"
      :getList="getSeriesList"
      :hasFooter="true"
      :footer="seriesDialogFooter"
      @customEvent="changeSeriesDialog"
      @getSelectData="getSelectedSeries"
    >
    </ele-dialog-table>
  </div>
</template>

<script>
import { materialDialog } from './materialMixin'
import { regularDialog } from './regularMixin'
import { technologyDialog } from './technologyMixin'
import { seriesDialog } from './seriesMixin'
import { searchConfig, importFormDescDialog, rowConfig, pageConfig } from './config'

import { getList, rowCreate, rowUpdate, rowDel, rowDetail, getTechnologyList, getProcessList } from '@/api/process/mesProcessMaterial'
import { getDict } from '@/api/common'

import { popover } from '@/utils/judge'
import url from '@/axios/url'
const { minioUrl } = url()

export default {
  name: 'mesProcessMaterial',
  mixins: [
    materialDialog, // 物料弹窗
    regularDialog, // 正则表达式弹窗
    technologyDialog, // 工艺查询弹窗
    seriesDialog, // 系列查询弹窗
    pageConfig // 页面配置，表格上方按钮，表格列配置
  ],
  data() {
    return {
      title: null,
      visible: false, // 新增/编辑弹窗
      isLoading: false,
      loading: false,
      formDataDialog: {
        // 新增表单数据
        materialList: []
      },
      searchConfig,
      getList,
      getTechnologyList, // 获取工艺列表
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection',
          fixed: 'left'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'type',
          label: $i18n.t('mesProcessMaterial.type'),
          minWidth: 80,
          fixed: 'left',
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getDict('process_material_type')
            return list.data.result
          }
        },
        {
          prop: 'processCode',
          label: $i18n.t('mesProcessMaterial.processCode'),
          minWidth: 120,
          fixed: 'left',
          showOverflowTooltip: true
        },
        {
          prop: 'processName',
          label: $i18n.t('mesProcessMaterial.processName'),
          minWidth: 120,
          render: (h, scope) => {
            return popover(scope.row.processName, h, 200)
          },
          fixed: 'left'
        },
        {
          prop: 'materialCode',
          label: $i18n.t('mesProcessMaterial.materialCode'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'materialName',
          label: $i18n.t('mesProcessMaterial.materialName'),
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'materialSpecification',
          label: $i18n.t('mesProcessMaterial.materialSpecification'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'prodCode',
          label: $i18n.t('mesProcessMaterial.prodCode'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'prodName',
          label: $i18n.t('mesProcessMaterial.prodName'),
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'technologyCode',
          label: $i18n.t('mesProcessMaterial.technologyCode'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'technologyName',
          label: $i18n.t('mesProcessMaterial.technologyName'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'technologyVersion',
          label: $i18n.t('mesProcessMaterial.versionNumber'),
          minWidth: 120
        },
        {
          prop: 'seriesCode',
          label: $i18n.t('mesProcessMaterial.seriesCoding'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'seriesName',
          label: $i18n.t('mesProcessMaterial.seriesName'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'regularCode',
          label: $i18n.t('mesProcessMaterial.materialRegularCode'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'regularName',
          label: $i18n.t('mesProcessMaterial.materialRegularName'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'regularContent',
          label: $i18n.t('mesProcessMaterial.materialRegularContent'),
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'isKey',
          label: $i18n.t('mesProcessMaterial.keyMaterial'),
          minWidth: 100,
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getDict('yes_or_not')
            return list.data.result
          }
        },
        {
          prop: 'createByName',
          label: $i18n.t('common.createByName'),
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: $i18n.t('common.createTime'),
          width: 170
        },
        {
          prop: 'updateByName',
          label: $i18n.t('common.updateByName'),
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'updateTime',
          label: $i18n.t('common.updateTime'),
          width: 170
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          width: 160,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ],
      selectedRowIndex: 0, // 当前正在修改的行的索引
      formDataCache: {}, // 新增表单时的数据缓存
      currentField: 'product', // 打开物料查询弹窗，返回的结果赋值给哪个字段，是产品字段(product)还是物料列表(materialList)
      dialogStatus: 'add', // 弹窗的功能，是编辑(edit)还是新增(add)
      processOptions: [],
      otherData: {} // 其他数据
    }
  },
  computed: {
    otherParam() {
      return {
        // 是否可以多选
        isMultiple: this.currentField === 'materialList'
      }
    }
  },
  methods: {
    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const fnc = {
        add: () => {
          this.disableFields(false)
          this.dialogStatus = 'add'
          this.formDataDialog = {
            materialList: []
          }
          this.formDataCache = {}
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm($i18n.t('common.deleteBatch', { name: $i18n.t('mesProcessMaterial.name') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.id).join(',')
            this.rowDel(ids)
          })
        },
        import: () => {
          this.importDialogData = {}
          this.importVisible = true
        },
        exportExcel: () => {
          var urlexportExcel = `${minioUrl}/mes-template/工序关联物料模板.xls`
          // console.log('aaaaaaa=', urlexportExcel)
          window.open(urlexportExcel)
        }
      }
      fnc[data.handleName]()
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        edit: () => {
          this.disableFields(false)
          this.dialogStatus = 'edit'
          this.rowDetail(row.id)
        },
        detail: () => {
          this.disableFields(true)
          this.dialogStatus = 'detail'
          this.rowDetail(row.id)
        },
        delete: () => {
          this.$confirm($i18n.t('common.deleteSingle', { name: $i18n.t('mesProcessMaterial.name') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowDel(row.id)
          })
        }
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true
      // 数据处理
      if (data.type === '0') {
        data.processCode = data.technologyProcess
      } else {
        data.processCode = data.otherProcess
      }
      // 如果类型是产品，新增的时候需要追加2个字段，系列编码和系列名称
      if (data.type === '1') {
        data['seriesCode'] = this.otherData['seriesCode'] || ''
        data['seriesName'] = this.otherData['seriesName'] || ''
      }
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
          this.formDataCache = {}
        })
    },
    // 新增/编辑提交事件
    handleSubmit(data) {
      if (this.isLoading) return // 判断状态
      const params = this.formDataDialog.id ? { title: $i18n.t('common.editSuccess'), api: rowUpdate, data } : { title: $i18n.t('common.addSuccess'), api: rowCreate, data }
      this.doSubmit(params)
    },
    // 删除
    rowDel(data) {
      this.loading = true
      rowDel(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    // 获取详情
    async rowDetail(id) {
      const res = await rowDetail(id)
      this.formDataDialog = res.data.result
      this.formDescDialog['specification'] = this.formDescDialog['prodSpecification']
      this.formDataDialog['versionNumber'] = this.formDataDialog['technologyVersion']
      if (res.data.result.type === '0') {
        const optionsRes = await getProcessList('0', this.formDataDialog.technologyId)
        this.processOptions = optionsRes.data.result
        this.$nextTick(() => {
          this.$set(this.formDataDialog, 'technologyProcess', this.formDataDialog['processCode'])
        })
      } else {
        this.formDataDialog['otherProcess'] = this.formDataDialog['processCode']
      }
      this.visible = true
    },
    // 刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    },
    // 新增物料
    handleAddMaterial(field = 'product') {
      this.currentField = field
      this.materialDialogVisible = true
    }
  },
  watch: {
    'formDataDialog.type': {
      handler(val) {
        if (this.formDataCache[val]) {
          this.formDataDialog = { ...this.formDataDialog, ...this.formDataCache[val] }
        } else {
          if (val !== '0') {
            // this.formDataDialog['otherProcess'] = '';
          }
        }
      }
    },
    formDataDialog: {
      handler(val) {
        if (val.type) {
          // 切换不同的类型时，表单数据需要保存下来，表格数据不需要保存
          this.formDataCache[val.type] = JSON.parse(JSON.stringify(this.formDataDialog))
          delete this.formDataCache[val.type]['materialList']
        }
      },
      immediate: true,
      deep: true
    },
    visible(val) {
      !val && (this.formDataCache = {})
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .material-regular-btn {
  display: flex;
  .el-input-group__append {
    display: flex;
    align-items: center;
  }
}
</style>
